package com.sxyjhh.service.data_exchange;

import com.sxyjhh.common.DBConfig;
import com.sxyjhh.dbutil.basic.ConstConfig;
import com.sxyjhh.dbutil.basic.DBQueryUtils;
import com.sxyjhh.dbutil.utils.DBInfoUtil;
import com.sxyjhh.dbutil.utils.PageInfo;
import com.sxyjhh.schedule.TaskRunnable;
import com.sxyjhh.schedule.TaskSchedulerManager;
import com.sxyjhh.service.insert_csafetycertificate.InsertCsafetycertificate_InsertCsafetycertificatePort_Client;
import com.sxyjhh.service.insert_person_security_certificate.InsertPersonStyCertificate_InsertPersonStyCertificatePort_Client;
import com.sxyjhh.utils.CommonUtils;
import com.sxyjhh.utils.FtpUtil;
import com.sxyjhh.utils.util.XaUtil;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/6/14.
 */
//建筑施工企业安管人员安全生产考核信息
public class PollingRunnableAqry extends TaskRunnable {

    private String tabName;
    private String key;

    private String ip = DBConfig.readPop("output.datasource.ip");
    private String dbName = DBConfig.readPop(" output.datasource.db.name");
    private String userName = DBConfig.readPop("output.datasource.username");
    private String password = DBConfig.readPop("output.datasource.password");
    private String port = DBConfig.readPop("output.datasource.port");
    private String type = DBConfig.readPop("output.datasource.type");
    private String imagesTabName = DBConfig.readPop("IMAGES.TABLE.NAME");

    private FTPClient ftpClient = new FTPClient();

    public PollingRunnableAqry(String tabName, String key) {
        this.taskId = "polling-" + tabName;
        this.tabName = tabName;
        this.key = key;
    }

    @Override
    public synchronized void run() {
        System.out.println("——————————————————————ThreadName————————————————————————");
        System.out.println(Thread.currentThread().getName());
        System.out.println("——————————————————————TaskName————————————————————————");
        System.out.println(taskId);
        System.out.println("——————————————————————possTime————————————————————————");
        System.out.println(CommonUtils.YYYYMMDDHHMMSS.format(new Date()));


        String tableName = null;
        // tableName = DBConfig.AQRY_CONTROL.poll(100, TimeUnit.MILLISECONDS);
        tableName = "DAQ_CF_Person_BaseInfo_18EB0020AE944469BB9A20BC16F62801_polling";
           /* //tableName = "daq_cf_ent_safetycerti_b36d7dac5d70444195dc1dfaa39f6f33_polling";
            tableName = "DAQ_CF_Person_BaseInfo_18EB0020AE944469BB9A20BC16F62801_polling";*/
        if (XaUtil.isEmpty(tableName)) {
            return;
        }

        String url = "";
        ConstConfig.DBType dbType = ConstConfig.DBType.valueOf(Integer.valueOf(type));
        if ("3".equals(type)) {
            url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useInformationSchema=true&useSSL=false";;
        } else {
            url = DBInfoUtil.getDBUrl(dbType, ip, port, dbName);
        }


        DBQueryUtils dbQueryUtils = new DBQueryUtils(DBInfoUtil.getDBDriverName(dbType),
                url, userName, password, 5);

        try {
            FtpUtil.getInstance().connect(ftpClient, "192.168.2.180", 2121, "yjhh", "a1b2c3d4!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        pushData(tableName, dbQueryUtils);
    }


        //推送数据

    private void pushData(String tableName, DBQueryUtils dbQueryUtils) {

        int outCount = 0;
        try {
            List countList = dbQueryUtils.queryData("select count(1) as cut from " + tableName);
            if (!XaUtil.isEmpty(countList)) {
                JSONObject countJson = JSONObject.fromObject(countList.get(0));
                outCount = (int) countJson.get("cut");
            }

            int num = 1000;
            int batch = (outCount / num) + (outCount % num != 0 ? 1 : 0);

            for (int i = 0; i < batch; i++) {
                PageInfo pageInfo = dbQueryUtils.queryTableDataByPaging(dbName, tableName, i + 1, num, "select * from " + tableName);


                List<Map> resultlist = pageInfo.getResultList();

                for (Map resMap : resultlist) {
                    JSONObject jsonObject = JSONObject.fromObject(resMap);
                    String fid = jsonObject.get(key) + "";
                    List data = dbQueryUtils.queryData("select FCONTENT as path  from " + imagesTabName + " where FLINKID ='" + fid + "'");
                    String image = "";
                    if (!XaUtil.isEmpty(data)) {
                        JSONObject countJson = JSONObject.fromObject(data.get(0));
                        String path = (String) countJson.get("path");
                        image = ftpDownload(path);

                    }
                    jsonObject.put("PHOTO", image);

                    jsonObject.put("ID_CARDS_TYPE", getDicCode(jsonObject.get("ID_CARDS_TYPE") + "", "zj"));
                    jsonObject.put("EDULEVEL", getDicCode(jsonObject.get("EDULEVEL") + "", "xl"));
                    jsonObject.put("PERSON_TYPE", getDicCode(jsonObject.get("PERSON_TYPE") + "", "ry"));
                    jsonObject.put("CERTIFICATE_AUTHORITY", "陕西省住房和城乡建设厅");
                    jsonObject.put("CERTIFICATE_STATE", getDicCode(jsonObject.get("CERTIFICATE_STATE") + "", "zt"));


                    String pushData = "{'PERSON_SECURITY_CERTIFICATE':" + jsonObject.toString() + "}";
                    System.out.println(pushData);
                    String result = InsertPersonStyCertificate_InsertPersonStyCertificatePort_Client.push(pushData);
                    System.out.println(result);
                    if (result.contains("200")) {
                        String keyValue = (String) resMap.get(key);
                        deleteData(tableName, key, keyValue, dbQueryUtils);
                    }
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //删除推送成功的数据
    private boolean deleteData(String tableNmae, String key, String keyValue, DBQueryUtils dbQueryUtils) {
        boolean flag = true;

        StringBuilder sql = new StringBuilder("delete from ");
        sql.append(tableNmae);
        sql.append(" where ");
        sql.append(key);
        sql.append(" = '");
        sql.append(keyValue);
        sql.append("' ");
        System.out.println(sql.toString());
        try {
            flag = dbQueryUtils.execDDLSql(sql.toString());
        } catch (SQLException e) {

            e.printStackTrace();
        }
        return flag;
    }

    private String ftpDownload(String path) {


        String imgBase64 = "";
        try {
            byte[] imageByte = FtpUtil.getInstance().download(ftpClient, path);
            if (!XaUtil.isEmpty(imageByte)) {
                imgBase64 = Base64.encodeBase64String(imageByte);
                return imgBase64;
            } else {
                return imgBase64;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return imgBase64;
        }
    }

    private String getDicCode(String s, String type) {
        String dicCode = "";

        if ("ry".equals(type)) {
            if ("C证人员".equals(s)) {
                dicCode = "03";
            }
            if ("C3证人员".equals(s)) {
                dicCode = "06";
            }
            if ("C2证人员".equals(s)) {
                dicCode = "05";
            }
            if ("C1证人员".equals(s)) {
                dicCode = "04";
            }
            if ("B证人员".equals(s)) {
                dicCode = "02";
            }
            if ("A证人员".equals(s)) {
                dicCode = "01";
            }

        }
        if ("zj".equals(type)) {
            if ("身份证".equals(s)) {
                dicCode = "01";
            }
            if ("军官证".equals(s)) {
                dicCode = "02";
            }
            if ("其他".equals(s)) {
                dicCode = "99";
            }
        }
        if ("zt".equals(type)) {
            if ("2".equals(s)) {
                dicCode = "01";
            }
            if ("-1".equals(s)) {
                dicCode = "04";
            }
        }
        if ("xl".equals(type)) {
            if ("博士".equals(s) || "博士后".equals(s)) {
                dicCode = "01";
            }
            if ("无".equals(s)) {
                dicCode = "99";
            }

            if ("大专".equals(s)) {
                dicCode = "04";
            }
            if ("中专".equals(s)) {
                dicCode = "05";
            }
            if ("本科".equals(s)) {
                dicCode = "03";
            }
            if ("中专以下(含高中初中)".equals(s)) {
                dicCode = "06";
            }
            if ("硕士".equals(s)) {
                dicCode = "02";
            }
        }
        return dicCode;
    }
}
